package cn.easyplatform.studio.web.editors.project;

import cn.easyplatform.lang.Strings;
import cn.easyplatform.studio.StudioApp;
import cn.easyplatform.studio.cmd.exportAll.GetMenuInfoCmd;
import cn.easyplatform.studio.cmd.exportAll.PagingMenuInfoCmd;
import cn.easyplatform.studio.cmd.exportAll.RootMenuInfoCmd;
import cn.easyplatform.studio.utils.StudioUtil;
import cn.easyplatform.studio.utils.WebUtils;
import cn.easyplatform.studio.vos.MenuInfoVo;
import cn.easyplatform.studio.vos.QueryMenuInfoVo;
import cn.easyplatform.studio.web.layout.WorkbenchController;
import org.zkoss.util.resource.Labels;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.Events;
import org.zkoss.zk.ui.util.Clients;
import org.zkoss.zul.*;
import org.zkoss.zul.event.PagingEvent;
import org.zkoss.zul.event.ZulEvents;

import java.util.ArrayList;
import java.util.List;

public class MenuExportEditor extends DictExportEditor {
    private Textbox code;
    private Textbox parentCode;
    private Textbox entity;

    private MenuInfoVo searchVo;
    private List<MenuInfoVo> allList;
    private QueryMenuInfoVo queryMenuInfoVo;
    public MenuExportEditor(WorkbenchController workbench, String id) {
        super(workbench, id);
    }

    @Override
    protected void dispatch(Event evt) {
        if (evt.getTarget() == showPaging) {// 分页
            PagingEvent pe = (PagingEvent) evt;
            int pageNo = pe.getActivePage() + 1;
            queryMenuInfoVo = StudioApp.execute(showPaging,
                    new PagingMenuInfoCmd(searchVo, showPaging.getPageSize(), pageNo, allList));
            redrawList(queryMenuInfoVo.getMenuVoList());
        } else if (evt.getTarget() instanceof Treeitem) {
            if (Events.ON_OPEN.equals(evt.getName())) {
                Treeitem item = (Treeitem) evt.getTarget();
                MenuInfoVo vo = item.getValue();
                queryMenuInfoVo = StudioApp.execute(item, new RootMenuInfoCmd(queryMenuInfoVo, vo, allList));
                redrawList(queryMenuInfoVo.getMenuVoList());
            }
        } else if (evt.getName().equals(Events.ON_CLICK)) {
            Component comp = evt.getTarget();
            if (comp.getId().equals("menuExport_textbox_query")) {
                searchVo = new MenuInfoVo();
                searchVo.setMenuId(code.getValue());
                searchVo.setName(name.getValue());
                searchVo.setParentMenuId(parentCode.getValue());
                searchVo.setTasks(parentCode.getValue());
                searchVo.setTasks(entity.getValue());
                queryMenuInfoVo = StudioApp.execute(showPaging,
                        new PagingMenuInfoCmd(searchVo, showPaging.getPageSize(), 1, allList));
                if (Double.valueOf(queryMenuInfoVo.getTotalSize()) / Double.valueOf(showPaging.getPageSize()) <= 1.0)
                    showPaging.setVisible(false);
                else {
                    showPaging.setVisible(true);
                    showPaging.setActivePage(0);
                    showPaging.setTotalSize(queryMenuInfoVo.getTotalSize());
                }
                allListCheck.setChecked(false);
                pageListCheck.setChecked(false);
                revListCheck.setChecked(false);
                checkPage = -1;
                redrawList(queryMenuInfoVo.getMenuVoList());
            } else if (comp.getId().equals("menuExport_image_chooseAllBtn")) {
                select(false);
            } else if (comp.getId().equals("menuExport_image_chooseBtn")) {
                select(true);
            } else if (comp.getId().equals("menuExport_image_removeBtn")) {
                unselect(true);
            } else if (comp.getId().equals("menuExport_image_removeAllBtn")) {
                unselect(false);
            } else if (comp.getId().equals("menuExport_toolbarbutton_export")) {
                export(comp);
            } else if (comp instanceof Treerow) {
                comp = (Treerow) comp;
                Treeitem currentItem = (Treeitem) comp.getParent();
                if (currentItem.isSelected() == true) {
                    while (currentItem.getParentItem() != null) {
                        currentItem.getParentItem().setSelected(true);
                        currentItem = currentItem.getParentItem();
                    }
                }
            }
        } else if (evt.getName().equals(Events.ON_CHECK)) {
            Checkbox r = (Checkbox) evt.getTarget();
            doCheck(r);
        }
    }

    @Override
    public void create(Object... args) {
        Idspace is = createPanel(Labels.getLabel("menu.repo.export.menu"), "~./images/menu.gif",
                "~./include/editor/project/menuExport.zul");
        code = (Textbox)is.getFellow("menuExport_textbox_code");
        name = (Textbox)is.getFellow("menuExport_textbox_name");
        parentCode = (Textbox)is.getFellow("menuExport_textbox_parentCode");
        entity = (Textbox)is.getFellow("menuExport_textbox_entity");
        this.sources = (Tree)is.getFellow("menuExport_tree_sources");
        this.targets = (Listbox)is.getFellow("menuExport_listbox_targets");
        this.comment = (Textbox) is.getFellow("menuExport_textbox_comment");
        this.showPaging = (Paging) is.getFellow("menuExport_paging_showPaging");
        Button searchBtn = (Button)is.getFellow("menuExport_textbox_query");
        searchBtn.addEventListener(Events.ON_CLICK, this);
        this.allListCheck = (Checkbox)is.getFellow("menuExport_checkbox_checkAll");
        this.allListCheck.addEventListener(Events.ON_CHECK, this);
        this.pageListCheck = (Checkbox)is.getFellow("menuExport_checkbox_checkPage");
        this.pageListCheck.addEventListener(Events.ON_CHECK, this);
        this.revListCheck = (Checkbox)is.getFellow("menuExport_checkbox_checkRev");
        this.revListCheck.addEventListener(Events.ON_CHECK, this);
        is.getFellow("menuExport_image_chooseAllBtn").addEventListener(Events.ON_CLICK, this);
        is.getFellow("menuExport_image_chooseBtn").addEventListener(Events.ON_CLICK, this);
        is.getFellow("menuExport_image_removeBtn").addEventListener(Events.ON_CLICK, this);
        is.getFellow("menuExport_image_removeAllBtn").addEventListener(Events.ON_CLICK, this);
        is.getFellow("menuExport_toolbarbutton_export").addEventListener(Events.ON_CLICK, this);
        redraw();
    }

    private void redraw() {
        allList = StudioApp.execute(new GetMenuInfoCmd(null, null));
        queryMenuInfoVo = StudioApp.execute(new PagingMenuInfoCmd(null, showPaging.getPageSize(), 1, allList));
        if (Double.valueOf(queryMenuInfoVo.getTotalSize()) / Double.valueOf(showPaging.getPageSize()) <= 1.0)
            showPaging.setVisible(false);
        else {
            showPaging.setVisible(true);
            showPaging.setTotalSize(queryMenuInfoVo.getTotalSize());
            showPaging.addEventListener(ZulEvents.ON_PAGING, this);
        }
        redrawList(queryMenuInfoVo.getMenuVoList());
    }

    private void redrawList(List<MenuInfoVo> list) {
        sources.clear();
        Treechildren treechildren = null;
        if (null == sources.getTreechildren()) {
            treechildren = new Treechildren();
            sources.appendChild(treechildren);
        }
        else {
            treechildren = sources.getTreechildren();
        }
        allTreechildren(treechildren, list);
    }
    private Treechildren allTreechildren(Treechildren children, List<MenuInfoVo> list) {
        for (MenuInfoVo vo : list) {
            final Treeitem item = new Treeitem();
            item.setValue(vo);
            item.setTooltiptext(vo.getTasks());
            Treerow row = new Treerow();
            row.setHeight("32px");
            row.appendChild(new Treecell(vo.getMenuId()));
            row.appendChild(new Treecell(vo.getName()));
            row.appendChild(new Treecell(vo.getImage()));
            row.appendChild(new Treecell(vo.getOrderNo()));
            row.appendChild(new Treecell(vo.getParentMenuId()));
            row.appendChild(new Treecell(vo.getDesp()));
            row.appendChild(new Treecell(vo.getTasks()));
            row.addEventListener(Events.ON_CLICK, this);
            item.appendChild(row);

            boolean isAddRoot = false;
            if (null != vo.getChildrenList() && vo.getChildrenList().size() != 0)
            {
                Treechildren ch = allTreechildren(new Treechildren(), vo.getChildrenList());
                item.appendChild(ch);
            } else {
                if (Strings.isBlank(vo.getParentMenuId()) || vo.getParentMenuId().equals(" "))
                    isAddRoot = true;
            }

            if (isAddRoot == true) {
                Treechildren childrenTree = new Treechildren();
                item.appendChild(childrenTree);
                item.setOpen(false);
                item.addEventListener(Events.ON_OPEN, this);
            }
            if (checkItem == CheckItem.SelectedAllItem)
                item.setSelected(true);
            else if ((checkItem == CheckItem.UnSelectedAllItem))
                item.setSelected(false);
            else if (checkPage == showPaging.getActivePage() + 1 && checkItem == CheckItem.SelectedPageItem)
                item.setSelected(true);
            else
                item.setSelected(false);
            children.appendChild(item);
        }
        return children;
    }

    private void select(boolean selectFlag) {
        for (Treeitem sel : sources.getItems()) {
            if (selectFlag && !sel.isSelected())
                continue;
            if (sel.getValue() != null) {
                boolean exists = false;
                MenuInfoVo s = sel.getValue();
                for (Listitem li : targets.getItems()) {
                    MenuInfoVo t = li.getValue();
                    if (s.getMenuId().equals(t.getMenuId())) {
                        exists = true;
                        break;
                    }
                }
                if (!exists) {
                    Listitem li = new Listitem();
                    li.appendChild(new Listcell(s.getMenuId()));
                    li.appendChild(new Listcell(s.getName()));
                    li.appendChild(new Listcell(s.getImage()));
                    li.appendChild(new Listcell(s.getOrderNo()));
                    li.appendChild(new Listcell(s.getParentMenuId()));
                    li.appendChild(new Listcell(s.getDesp()));
                    li.appendChild(new Listcell(s.getTasks()));
                    li.setValue(s);
                    targets.appendChild(li);
                }
            }
        }
    }

    private void unselect(boolean selectedFlag) {
        if (selectedFlag) {
            if (targets.getSelectedCount() > 0) {
                List<Listitem> items = new ArrayList<Listitem>();
                for (Listitem li : targets.getSelectedItems())
                    items.add(li);
                for (Listitem li : items)
                    li.detach();
            }
        } else
            targets.getItems().clear();
    }

    //导出
    protected void export(Component btn) {
        if (targets.getItems().isEmpty()) {
            WebUtils.showError(Labels.getLabel("editor.export.empty"));
            return;
        }
        if (Strings.isBlank(comment.getValue())) {
            WebUtils.notEmpty(Labels.getLabel("editor.export.comment"));
            return;
        }
        Clients.clearWrongValue(btn);
        //打包保存
        List<MenuInfoVo> menuVos = new ArrayList<>();
        for (Listitem li : targets.getItems()) {
            MenuInfoVo e = li.getValue();
            menuVos.add((MenuInfoVo)e.clone());
        }
        StudioUtil.exportMenu(menuVos, comment.getValue());
    }
}
